//
//  ReservationOKTableViewController.m
//  LoveAttention
//
//  Created by 鞠超 on 15/12/30.
//  Copyright © 2015年 JC. All rights reserved.
//

#import "ReservationOKTableViewController.h"
#import "ReservationOKTableViewCell.h"
#import "ReservationOKViewController.h"
#import "Modle_reservation.h"

#import "MJRefresh.h"
#import "DataProvider.h"
#import "SVProgressHUD.h"
#import "UIImageView+WebCache.h"
@interface ReservationOKTableViewController ()

@property (nonatomic, strong) NSMutableArray * arr_data;

@property (nonatomic, assign) NSInteger index;

@end

@implementation ReservationOKTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self p_navigationController];
    
//    [self example01];
    //注册
    [self.tableView registerClass:[ReservationOKTableViewCell class] forCellReuseIdentifier:@"cell_ReservationOK"];
    //清除空余分割线
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    [self p_data];

}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [self example01];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - navigationController
- (void)p_navigationController
{
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    self.navigationItem.title = @"预约确定";
    
    UIButton * btn = [UIButton buttonWithType:(UIButtonTypeSystem)];
    [btn setBackgroundImage:[UIImage imageNamed:@"返回"] forState:(UIControlStateNormal)];
        btn.frame = CGRectMake(10, 20, 25, 30);
    [btn addTarget:self action:@selector(leftBarButtonItemAction:) forControlEvents:(UIControlEventTouchUpInside)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
}
//点击事件(左)
- (void)leftBarButtonItemAction:(UIBarButtonItem *)bar
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arr_data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Modle_reservation * model = self.arr_data[indexPath.row];
    
    ReservationOKTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell_ReservationOK" forIndexPath:indexPath];
    
    //加数据
    NSString *url = [NSString stringWithFormat:@"%@upload/%@",Url,model.headportain];
    [cell.image sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"头像"]];
    
    cell.name.text = model.username;
    if(model.sign.length == 0)
    {
        cell.detail.text = @"未设置";
    }
    else
    {
        cell.detail.text = model.sign;
    }
    cell.date.text = model.datetime;
    
    switch ([model.rstate intValue]) {
        case 0:
            cell.ok.text = @"预约申请";
            break;
        case 1:
            cell.ok.text = @"预约同意";
            break;
        case 2:
            cell.ok.text = @"预约取消";
            break;
        case 3:
            cell.ok.text = @"预约完成";
            break;
        default:
            break;
    }

    return cell;
}
//行高
- (CGFloat )tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 75;
}
//点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Modle_reservation * model = self.arr_data[indexPath.row];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    ReservationOKViewController * reservationOKViewController = [[ReservationOKViewController alloc] init];
    
    reservationOKViewController.reseratid = model.reseratid;
    
    reservationOKViewController.rstate = model.rstate;
    
    [self showViewController:reservationOKViewController sender:nil];
}

//删除cell
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    //做删除操作，并调接口删除后台数据
    
    Modle_reservation * model = self.arr_data[indexPath.row];
    
    if([model.rstate intValue] == 2)
    {
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定从列表中删除该订单" preferredStyle:(UIAlertControllerStyleAlert)];
        
        [self presentViewController:alert animated:YES completion:^{
            
        }];
        
        UIAlertAction * action = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alert addAction:action];
        
        UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
            self.index = indexPath.row;
            
            DataProvider * dataprovider = [[DataProvider alloc] init];
            
            [dataprovider setDelegateObject:self setBackFunctionName:@"ReservationDelete:"];
            
            [dataprovider ReservationDeleteWith:model.reseratid];
            
        }];
        
        [alert addAction:action1];
    }
    else
    {
        UIAlertView * alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"该状态不能删除" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles: nil];
        [alert show];
    }
}

#pragma mark - 数据
- (void)p_data
{
    DataProvider * dataprovider = [[DataProvider alloc] init];
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    [dataprovider setDelegateObject:self setBackFunctionName:@"Reservation:"];
    
    [dataprovider ReservationWith:[defaults objectForKey:@"merchantid"] andpagenumber:@"1" andpagesize:@"50"];
}

- (void)Reservation:(id )dict
{
    //    NSLog(@"%@",dict);
    
    self.arr_data = nil;
    
    if ([dict[@"status"][@"succeed"] intValue] == 1) {
        @try
        {
            for (NSDictionary * dic in dict[@"data"]) {
                                
                if([dic[@"rstate"] intValue] != 3)
                {
                    Modle_reservation * model = [[Modle_reservation alloc] init];
                    
                    [model setValuesForKeysWithDictionary:dic];
                    
                    [self.arr_data addObject:model];
                }
                
            }
        }
        @catch (NSException *exception) {
            
        }
        @finally {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                //刷新tableView(记住,要更新放在主线程中)
                
                [self.tableView reloadData];
            });
        }
    }
    else
    {
        [SVProgressHUD showErrorWithStatus:dict[@"status"][@"errdesc"] maskType:SVProgressHUDMaskTypeBlack];
    }
}

#pragma mark - 预约删除
- (void)ReservationDelete:(id )dict
{
    
    NSLog(@"%@",dict);
    
    if ([dict[@"status"][@"succeed"] intValue] == 1) {
        @try
        {
            [self.arr_data removeObjectAtIndex:self.index];
            
            [SVProgressHUD showSuccessWithStatus:@"删除成功" maskType:(SVProgressHUDMaskTypeBlack)];
            
        }
        @catch (NSException *exception) {
            
        }
        @finally {
            
            [self.tableView reloadData];
            
        }
    }
    else
    {
        [SVProgressHUD showErrorWithStatus:dict[@"status"][@"errdesc"] maskType:SVProgressHUDMaskTypeBlack];
    }

}

#pragma mark - 懒加载
- (NSMutableArray *)arr_data
{
    if(_arr_data == nil)
    {
        self.arr_data = [NSMutableArray array];
    }
    
    return _arr_data;
}

#pragma mark - 下拉刷新
- (void)example01
{
    __weak __typeof(self) weakSelf = self;
    
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [weakSelf p_data];
        
        [weakSelf loadNewData];
        
    }];
    // 马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
}

-(void)example02
{
    __weak __typeof(self) weakSelf = self;
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf loadNewData];
        
    }];
    
}

- (void)loadNewData
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    });
    
}





@end
